import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { computed } from 'vue';

import { useAccess } from '@vben/access';
import { DictEnum } from '@vben/constants';
import { useUserStore } from '@vben/stores';

import { getDictOptions } from '#/utils/dict';
import { renderDict } from '#/utils/render';
import { productList } from '#/api/hm/product';
import {
  customerListByStaffId,
  customerListByStaffIds,
} from '#/api/hm/customer';
import { listUserByDeptId } from '#/api/system/user';
import { getPopupContainer } from '@vben/utils';

const { hasAccessByRoles } = useAccess();
const isAdmin = computed(() => {
  return hasAccessByRoles(['admin', 'superadmin', 'ceo', 'warehouse-manage']);
});

const useStore = useUserStore();

export const querySchema: FormSchemaGetter = () => [
  {
    component: 'Select',
    fieldName: 'recordProductType',
    defaultValue: 'CP',
    label: '产品类型',
    componentProps: {
      options: getDictOptions(DictEnum.HM_PRODUCT_TYPE),
    },
  },
  {
    component: 'Select',
    fieldName: 'recordProductId',
    label: '产品',
    componentProps: {
      allowClear: true,
      showSearch: true,
      optionFilterProp: 'label',
    },
    dependencies: {
      async componentProps(value) {
        if (value?.recordProductType) {
          let requestParams = {
            pageNum: 1,
            pageSize: 999,
            status: '0',
            productType: '',
          };
          if (value?.recordProductType === 'CP') {
            requestParams.productType = 'CP';
          } else {
            requestParams.productType = 'ZP';
          }
          const ret = await productList(requestParams);
          const dataSourceOptions = [];
          const transOptions = ret.rows.map((item) => ({
            label: item.productName,
            value: item.productId.toString(),
          }));
          dataSourceOptions.push(...transOptions);
          return { options: dataSourceOptions };
        }
        return {};
      },
      triggerFields: ['recordProductType'],
    },
  },
  {
    component: 'Select',
    componentProps: {
      options: getDictOptions(DictEnum.SYS_IN_OUT),
    },
    fieldName: 'recordType',
    label: '出/入类型',
  },
  {
    component: 'Select',
    fieldName: 'recordStartLocation',
    label: '出库地',
  },
  {
    component: 'Select',
    fieldName: 'recordEndLocation',
    label: '入库地',
  },
];

export const columns: VxeGridProps['columns'] = [
  { type: 'checkbox', width: 60 },
  {
    title: '产品名称',
    field: 'recordProductName',
  },
  {
    title: '产品类型',
    field: 'recordProductType',
    slots: {
      default: ({ row }) => {
        if (row.recordProductType) {
          return renderDict(row.recordProductType, DictEnum.HM_PRODUCT_TYPE);
        }
        return '-';
      },
    },
  },
  {
    title: '出/入库数量',
    field: 'recordNum',
  },
  {
    title: '出/入类型',
    field: 'recordType',
    slots: {
      default: ({ row }) => {
        if (row.recordType) {
          return renderDict(row.recordType, DictEnum.SYS_IN_OUT);
        }
        return '-';
      },
    },
  },
  {
    title: '出库地',
    field: 'recordStartLocationName',
  },
  {
    title: '入库地',
    field: 'recordEndLocationName',
  },
  {
    title: '外围市场',
    field: 'peripheralMarket',
  },
  {
    title: '操作时间',
    field: 'createTime',
  },
  {
    title: '是否入库',
    field: 'status',
    slots: {
      default: ({ row }) => {
        if (row.status) {
          return renderDict(row.status, DictEnum.RECEIPT_STATUS);
        }
        return '-';
      },
    },
  },
  {
    title: '备注',
    field: 'remark',
  },
  {
    field: 'action',
    fixed: 'right',
    slots: { default: 'action' },
    title: '操作',
    width: 180,
  },
];

export const modalSchema: FormSchemaGetter = () => [
  {
    label: '出入库id',
    fieldName: 'recordId',
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
  },
  {
    label: '商品类型',
    fieldName: 'recordProductType',
    component: 'RadioGroup',
    defaultValue: 'CP',
    componentProps: {
      options: getDictOptions(DictEnum.HM_PRODUCT_TYPE),
      buttonStyle: 'solid',
      optionType: 'button',
    },
    dependencies: {
      async componentProps(values) {
        return {
          async onChange() {
            values.recordProductId = undefined;
          },
        };
      },
      triggerFields: ['recordProductType'],
    },

    rules: 'selectRequired',
  },
  {
    label: '操作产品',
    fieldName: 'recordProductId',
    component: 'Select',
    rules: 'required',
    componentProps: {
      allowClear: true,
      showSearch: true,
      optionFilterProp: 'label',
    },
    dependencies: {
      async componentProps(value) {
        if (value?.recordProductType) {
          let requestParams = {
            pageNum: 1,
            pageSize: 999,
            status: '0',
            productType: '',
          };
          if (value?.recordProductType === 'CP') {
            requestParams.productType = 'CP';
          } else {
            requestParams.productType = 'ZP';
          }
          const ret = await productList(requestParams);
          const dataSourceOptions = [];
          const transOptions = ret.rows.map((item) => ({
            label: item.productName,
            value: item.productId.toString(),
          }));
          dataSourceOptions.push(...transOptions);
          return { options: dataSourceOptions };
        }
        return {};
      },
      triggerFields: ['recordProductType'],
    },
  },
  {
    label: '数量',
    fieldName: 'recordNum',
    component: 'InputNumber',
    rules: 'required',
    componentProps: {
      min: 0,
      precision: 2,
      label: '数量',
    },
    dependencies: {
      show: (values) => ![4, 5].includes(Number(values?.recordType)),
      triggerFields: ['recordType'],
    },
  },
  {
    label: '个人数量',
    fieldName: 'recordNum',
    component: 'InputNumber',
    rules: 'required',
    componentProps: {
      min: 0,
      precision: 2,
      label: '数量',
    },
    dependencies: {
      show: (values) => [4, 5].includes(Number(values?.recordType)),
      triggerFields: ['recordType'],
    },
  },
  {
    label: '是否主动入库',
    fieldName: 'isActive',
    component: 'Radio',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
  },
  {
    label: '类型',
    fieldName: 'recordType',
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      options: getDictOptions(DictEnum.SYS_IN_OUT),
      optionType: 'button',
    },
    dependencies: {
      componentProps(values) {
        values.isActive = values?.recordType === '2';
        const allOptions = getDictOptions(DictEnum.SYS_IN_OUT);
        let options = allOptions.filter(
          (opt) => ![2, 3, 6].includes(Number(opt.value)),
        );
        if (isAdmin.value) {
          options = allOptions.filter(
            (opt) => ![3].includes(Number(opt.value)),
          );
        }
        return {
          options: options,
        };
      },
      triggerFields: ['recordType'],
    },

    rules: 'selectRequired',
  },
  {
    label: '出库地',
    fieldName: 'recordStartLocation',
    component: 'Select',
    rules: 'required',
    defaultValue: useStore.userInfo?.deptId?.toString(),
    dependencies: {
      show: (values) =>
        values?.recordType === '1' || values?.recordType === '6',
      disabled: (values) => {
        if (isAdmin.value) {
          return false;
        }
        return values.recordType === '1';
      },
      triggerFields: ['recordType'],
    },
  },
  {
    label: '入库地',
    fieldName: 'recordEndLocation',
    defaultValue: useStore.userInfo?.deptId?.toString(),
    component: 'Select',
    rules: 'required',
    dependencies: {
      show: (values) => ![3, 4, 5, 6].includes(Number(values?.recordType)),

      disabled: (values) => {
        if (isAdmin.value) {
          return false;
        }
        return values.recordType === '2';
      },
      componentProps(values) {
        if (values.recordId) {
          return values.recordEndLocation;
        }
        values.recordEndLocation = undefined;
        if (values?.recordType === '2') {
          values.recordEndLocation = useStore.userInfo?.deptId?.toString();
        }

        return {};
      },
      triggerFields: ['recordType', 'recordId'],
    },
  },
  {
    label: '所属部门',
    component: 'TreeSelect',
    // 在drawer里更新 这里不需要默认的componentProps
    defaultValue: useStore.userInfo?.deptId?.toString(),
    fieldName: 'deptId',
    dependencies: {
      show: (values) =>
        [4].includes(Number(values?.recordType)) && isAdmin.value,
      triggerFields: ['recordType'],
    },
    rules: 'required',
  },
  {
    label: '员工',
    fieldName: 'employeeIds',
    component: 'Select',
    rules: 'required',
    help: '选择部门后, 将自动加载该部门下所有的员工',
    dependencies: {
      show: (values) => [4].includes(Number(values?.recordType)),
      async componentProps(values) {
        let deptId;
        if (!isAdmin.value) {
          deptId = useStore.userInfo?.deptId;
        } else {
          deptId = values.deptId;
        }
        const ret = await listUserByDeptId(deptId);
        const transOptions = ret.map((item) => ({
          label: item.userName,
          value: item.userId,
        }));
        const dataSourceOptions = [];
        dataSourceOptions.push(...transOptions);
        return {
          options: dataSourceOptions,
          getPopupContainer,
          mode: 'multiple',
          optionFilterProp: 'label',
          optionLabelProp: 'label',
          placeholder: '请先选择部门',
        };
      },
      triggerFields: ['recordType', 'deptId'],
    },
  },
  {
    label: '员工',
    fieldName: 'saleUsers',
    component: 'Select',
    rules: 'required',
    componentProps: {
      showSearch: true,
      optionFilterProp: 'label',
    },
    dependencies: {
      async componentProps(values) {
        const ret = await listUserByDeptId(values?.deptId);
        const transOptions = ret.map((item) => ({
          label: item.userName,
          value: item.userId,
        }));
        const dataSourceOptions = [];
        dataSourceOptions.push(...transOptions);
        return {
          options: dataSourceOptions,
          mode: 'multiple',
          async onChange() {
            if (values.saleUsers.length === 0) {
              values.customerIds = undefined;
            }
          },
        };
      },
      show: (values) => [5].includes(Number(values?.recordType)),

      triggerFields: ['recordType'],
    },
  },
  {
    label: '客户',
    fieldName: 'customerIds',
    component: 'Select',
    rules: 'required',
    help: '选择员工后, 将自动加载该员工下的所有客户',
    dependencies: {
      show: (values) => [5].includes(Number(values?.recordType)),
      async componentProps(values) {
        let userId;
        userId = values?.saleUsers;
        if (userId.length === 0) {
          return {};
        }
        const ret = await customerListByStaffIds(userId);
        const transOptions = ret.map((item) => ({
          label: item.customerName,
          value: item.customerId,
        }));
        const dataSourceOptions = [];
        dataSourceOptions.push(...transOptions);
        return {
          options: dataSourceOptions,
          mode: 'multiple',
          optionFilterProp: 'label',
          optionLabelProp: 'label',
          placeholder: '请先选择员工',
        };
      },
      triggerFields: ['recordType', 'recordId', 'saleUsers'],
    },
  },
  {
    label: '外围市场',
    fieldName: 'peripheralMarket',
    component: 'Input',
    dependencies: {
      show: (values) => [6].includes(Number(values?.recordType)),
      triggerFields: ['recordType'],
    },
  },
  {
    label: '备注',
    fieldName: 'remark',
    component: 'Input',
  },
];
